import Vue from 'vue';
import {
    api,
} from '@/lib/api';
import {
    url,
    isArray,
    currency,
    getRebateKey,
    getOrderKey,
    getUserDataKey,
    getRankKey,
    dateFormat,
    getMapKey,
} from '@/lib/utils';

import { Module } from 'vuex';
import { RootState } from '@/types/store';

export interface ManageState {
    /** 订单列表 */
    orderListMap: {
        [orderKey: string]: ListWrap<number> & ListReq;
    };
    orderMap: {
        [orderId: number]: Manage.OrderListItem;
    };
    /** 交易额排行榜 */
    rankListMap: {
        [rankKey: string]: ListWrap<Manage.RankItem> & ListReq;
    };
    /** 奖金列表 */
    rebateListMap: {
        [rebateKey: string]: ListWrap<number> & ListReq;
    };
    rebateMap: {
        [rebateId: number]: Manage.RebateItem;
    };
    /** 看板数据 */
    userDataListMap: {
        [userDataKey: string]: ListWrap<Manage.UserData> & ListReq;
    };
    productSpecMap: any;
    selectedGoodsSpecMap: any;
    sureGoodsSpecMap: any;
    statisticsMap: {
        [MapKey_start_end_name_userId_shopId: number]: Manage.Statistics;
    };
    userSearchMap: {
        [search: string]: User.SearchResult[];
    };
}

const m: Module<ManageState, RootState> = {
    namespaced: true,
    state: {
        orderListMap: {},
        orderMap: {},
        rankListMap: {},
        rebateListMap: {},
        rebateMap: {},
        userDataListMap: {},
        productSpecMap: {},
        selectedGoodsSpecMap: {},
        sureGoodsSpecMap: {},
        statisticsMap: {},
        userSearchMap: {},
    },
    mutations: {
        /**
         * 订单列表
         */
        initOrderList(state, { key }) {
            Vue.set(state.orderListMap, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatOrderList(state, { key, list }) {
            const idArr = [];
            for (const order of list) {
                if (isArray(order.detail)) {
                    for (const item of order.detail) {
                        item.price_text = currency(item.price);
                    }
                }
                Vue.set(state.orderMap, order.id, order);
                idArr.push(order.id);
            }
            state.orderListMap[key].list.push(...idArr);
        },
        setOrderListLoaded(state, { key, loaded }) {
            state.orderListMap[key].loaded = loaded;
        },
        finalPayOrderItem(state, { orderId }) {
            Vue.set(state.orderMap[orderId], 'final_payment', 1);
        },
        cancelFinalPayOrderItem(state, { orderId }) {
            Vue.set(state.orderMap[orderId], 'final_payment', 0);
        },
        endOrderItem(state, { orderId }) {
            Vue.set(state.orderMap[orderId], 'is_finish', 1);
        },
        hasDeliver(state, { orderId }) {
            Vue.set(state.orderMap[orderId], 'delivery', 2);
        },
        setOrderListReq(state, { key, req }) {
            state.orderListMap[key].req = req;
        },
        /** 交易额排行榜 */
        initRankList(state, { key }) {
            Vue.set(state.rankListMap, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatRankList(state, { key, list }) {
            state.rankListMap[key].list.push(...list);
        },
        setRankListLoaded(state, { key, loaded }) {
            state.rankListMap[key].loaded = loaded;
        },
        setRankListReq(state, { key, req }) {
            state.rankListMap[key].req = req;
        },
        /**
         * 奖励列表
         */
        initRebateList(state, { key }) {
            Vue.set(state.rebateListMap, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatRebateList(state, { key, list }) {
            const idArr = [];
            list.forEach(item => {
                Vue.set(state.rebateMap, item.id, item);
                idArr.push(item.id);
            });
            state.rebateListMap[key].list.push(...idArr);
        },
        setRebateListLoaded(state, { key, loaded }) {
            state.rebateListMap[key].loaded = loaded;
        },
        setRebateListReq(state, { key, req }) {
            state.rebateListMap[key].req = req;
        },
        /**
         * 看板数据列表
         */
        initUserDataList(state, { key }) {
            Vue.set(state.userDataListMap, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatUserDataList(state, { key, list }) {
            // const idArr = [];
            // list.forEach(item => {
            //     Vue.set(state.userDataMap, item.user_id, item);
            //     idArr.push(item.user_id);
            // });
            state.userDataListMap[key].list.push(...list);
        },
        setUserDataListLoaded(state, { key, loaded }) {
            state.userDataListMap[key].loaded = loaded;
        },
        setUserDataListReq(state, { key, req }) {
            state.userDataListMap[key].req = req;
        },
        setProductSpec(state, { key, detail }) {
            Vue.set(state.productSpecMap, key, detail);
        },
        /** 设置选择规格 */
        setSelectedGoodsSpec(state, { key, list }) {
            Vue.set(state.selectedGoodsSpecMap, key, JSON.parse(JSON.stringify(list)));
        },
        /** 重置选择规格 */
        resetSelectedGoodsSpec(state, { key }) {
            Vue.set(state.selectedGoodsSpecMap, key, JSON.parse(JSON.stringify(state.sureGoodsSpecMap[key])));
        },
        setSelectedGoodsSpecItemNumber(state, { key, specIndex, valIndex, number }) {
            Vue.set(state.selectedGoodsSpecMap[key][specIndex][valIndex], 'number', number);
        },
        /** 确认套餐规格 */
        setSureGoodsSpec(state, { key }) {
            Vue.set(state.sureGoodsSpecMap, key, JSON.parse(JSON.stringify(state.selectedGoodsSpecMap[key])));
        },
        setStatistics(state, { key, detail }) {
            Vue.set(state.statisticsMap, key, detail);
        },
        setUserSearchMap(state, { key, list }) {
            Vue.set(state.userSearchMap, key, list);
        },
    },

    actions: {
        /**
         * 搜索用户
         */
        async searchUser({ state, commit }, { search }) {
            const res = await api.get({
                url: `${url}/api/user/search`,
                data: {
                    search,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('setUserSearchMap', {
                    key: search,
                    list,
                });
            }
            return res;
        },
        /**
         * 获取订单列表
         */
        async getOrderList({ state, commit }, { offset, count, start, end, name, userId, referrerId, shopId, referrerLevel, level, forceUpdate }) {
            const key = getOrderKey({ start, end, name, userId, shopId, level, referrerId });
            let wrap = state.orderListMap[key];
            if (!wrap || forceUpdate) {
                commit('initOrderList', { key });
                wrap = state.orderListMap[key];
            }
            if (wrap.loaded || wrap.req) {
                return;
            }
            const listEnd = offset + count;
            const length = wrap.list.length;
            if (listEnd <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = listEnd - offset;
            }
            commit('setOrderListReq', { key, req: true });
            const data: any = {
                offset,
                count,
            };
            if (start) {
                data.start = start;
            }
            if (end) {
                data.end = dateFormat(new Date(end).valueOf() + 24 * 60 * 60 * 1000);
            }
            if (shopId) {
                data.shop_id = shopId;
            }
            if (userId) {
                data.user_id = userId;
            }
            if (name) {
                data.name = name;
            }
            if (referrerId) {
                data.referrer_id = referrerId;
            }
            if (referrerLevel) {
                data.referrer_level = referrerLevel;
            }
            if (level) {
                data.level = level;
            }
            const res = await api.post({
                url: `${url}/api/manage/order`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatOrderList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setOrderListLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setOrderListReq', { key, req: false });
            return res;
        },
        /**
         * 获取奖励列表
         */
        async getRebateList({ state, commit }, { offset, count, start, end, shopId, referrerLevel, referrerId, forceUpdate }) {
            const key = getRebateKey({ start, end, shopId, referrerId, referrerLevel });
            let wrap = state.rebateListMap[key];
            if (!wrap || forceUpdate) {
                commit('initRebateList', { key });
                wrap = state.rebateListMap[key];
            }
            if (wrap.loaded || wrap.req) {
                return;
            }
            const listEnd = offset + count;
            const length = wrap.list.length;
            if (listEnd <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = listEnd - offset;
            }
            commit('setRebateListReq', { key, req: true });
            const data: any = {
                offset,
                count,
            };
            if (start) {
                data.start = start;
            }
            if (end) {
                // data.end = end;
                data.end = dateFormat(new Date(end).valueOf() + 24 * 60 * 60 * 1000);
            }
            if (shopId) {
                data.shop_id = shopId;
            }
            if (referrerId) {
                data.referrer_id = referrerId;
            }
            if (referrerLevel) {
                data.referrer_level = referrerLevel;
            }
            const res = await api.post({
                url: `${url}/api/manage/rebate_list`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatRebateList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setRebateListLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setRebateListReq', { key, req: false });
            // console.log('getRebateKey', key, wrap);
            return res;
        },
        /**
         * 获取数据看板列表
         */
        async getUserDataList({ state, commit }, { offset, count, start, end, level, userId, referrerId, shopId, identity, search, forceUpdate }) {
            const key = getUserDataKey({ start, end, shopId, userId, identity, level, referrerId, search });
            let wrap = state.userDataListMap[key];
            if (!wrap || forceUpdate) {
                commit('initUserDataList', { key });
                wrap = state.userDataListMap[key];
            }
            // console.log(wrap, wrap.loaded, wrap.req);
            if (wrap.loaded || wrap.req) {
                return;
            }
            const listEnd = offset + count;
            const length = wrap.list.length;
            if (listEnd <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = listEnd - offset;
            }
            commit('setUserDataListReq', { key, req: true });
            const data: any = {
                offset,
                count,
                user_id: userId,
                search,
            };
            if (start) {
                data.start = start;
            }
            if (end) {
                data.end = dateFormat(new Date(end).valueOf() + 24 * 60 * 60 * 1000);
                // data.end = end;
            }
            if (shopId) {
                data.shop_id = shopId;
            }
            if (identity) {
                data.identity = identity;
            }
            if (level) {
                data.level = level;
            }
            if (referrerId) {
                data.referrerId = referrerId;
            }
            const res = await api.post({
                url: `${url}/api/manage/user_data`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatUserDataList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setUserDataListLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setUserDataListReq', { key, req: false });
            return res;
        },
        /**
         * 获取统计信息
         */
        async getStatistics({ state, commit }, data: { start: string | null; end: string | null; name: string | null; userId: string | null; shopId: number[] }) {
            const key = getMapKey(data);
            const res = await api.post({
                url: '/api/manage/statistics',
                data: {
                    shop_id: data.shopId,
                    start: data.start,
                    end: data.end ? dateFormat(new Date(data.end).valueOf() + 24 * 60 * 60 * 1000) : null,
                    name: data.name || null,
                    user_id: data.userId || null,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const detail = res.data.data;
                commit('setStatistics', {
                    key,
                    detail,
                });
            }
            return res;
        },
        /**
         * 获取规格
         */
        async getProductSpec({ state, commit }, { pkgId, orderId, forceUpdate }) {
            const key = `${pkgId}_${orderId}`;
            if (!forceUpdate && state.productSpecMap[key]) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/package/spec`,
                data: {
                    package_id: pkgId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const rdata = res.data.data;

                // 添加字段
                for (const item of rdata) {
                    for (const option of item.values) {
                        option.price = 0;
                    }
                }
                commit('setProductSpec', {
                    key,
                    detail: rdata,
                });
                const gift = state.orderMap[orderId].gift;
                const optionList = rdata.map((item) => {
                    return item.values.map(val => {
                        if (gift && gift.length) {
                            for (let i = 0; i < gift.length; i++) {
                                if (gift[i].id === val.id) {
                                    const tempGift = {
                                        ...gift[i],
                                        price: 0,
                                    };
                                    return Object.assign(val, tempGift);
                                }
                            }
                        }
                        return Object.assign(val, {
                            number: 0,
                        });
                    });
                    // return [ item.values[0] ];
                });
                // console.log('optionList', optionList);
                // const newOptionList = optionList.map(item => Object.assign(item, {
                //     number: 1,
                // }));
                commit('setSelectedGoodsSpec', {
                    key,
                    list: optionList,
                });
                commit('setSureGoodsSpec', {
                    key,
                });
            }
            return res;
        },
        async giveGift({ state, commit }, { orderId, spec }) {
            const res = await api.post({
                url: `${url}/api/manage/give`,
                data: {
                    id: orderId,
                    spec,
                },
            });
            return res;
        },
        async changePrice({ state, commit }, { orderId, price, isPrepay }) {
            const res = await api.post({
                url: `${url}/api/manage/price`,
                data: {
                    id: orderId,
                    price,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                if (isPrepay) {
                    Vue.set(state.orderMap[orderId], 'original_price', price);
                } else {
                    Vue.set(state.orderMap[orderId], 'price', price);
                }
            }
            return res;
        },
        /**
         * 完成订单
         */
        async finalPayment({ state, commit }, { orderId }) {
            const res = await api.post({
                url: `${url}/api/manage/final_payment`,
                data: {
                    id: orderId,
                },
            });
            if (res.data.status === 0) {
                commit('finalPayOrderItem', {
                    orderId,
                });
            }
            return res;
        },
        /**
         * 交货
         */
        async endOrder({ state, commit }, { orderId }) {
            const res = await api.post({
                url: `${url}/api/manage/finish`,
                data: {
                    id: orderId,
                },
            });
            if (res.data.status === 0) {
                commit('endOrderItem', {
                    orderId,
                });
            }
            return res;
        },
        /**
         * 发货
         */
        async hasDeliver({ state, commit }, { orderId }) {
            const res = await api.get({
                url: `${url}/api/manage/deliver`,
                data: {
                    id: orderId,
                },
            });
            if (res.data.status === 0) {
                commit('hasDeliver', {
                    orderId,
                });
            }
            return res;
        },
        async cancelFinalPayOrder({ state, commit }, { orderId }) {
            const res = await api.post({
                url: `${url}/api/manage/cancel_final_payment`,
                data: {
                    id: orderId,
                },
            });
            if (res.data.status === 0) {
                commit('cancelFinalPayOrderItem', {
                    orderId,
                });
            }
            return res;
        },
        /**
         * 获取订单列表
         */
        async getRankList({ state, commit }, { offset, count, shopId, level, interval, type, forceUpdate }) {
            const key = getRankKey({ level, interval, type });
            // console.log('key', key);
            let wrap = state.rankListMap[key];
            if (!wrap || forceUpdate) {
                commit('initRankList', { key });
                wrap = state.rankListMap[key];
            }
            // console.log(wrap, wrap.loaded, wrap.req);
            if (wrap.loaded || wrap.req) {
                return;
            }
            const listEnd = offset + count;
            const length = wrap.list.length;
            if (listEnd <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = listEnd - offset;
            }
            commit('setRankListReq', { key, req: true });
            const data: any = {
                offset,
                count,
                shop_id: shopId,
            };
            if (level) {
                data.level = level;
            }
            if (interval) {
                data.interval = interval;
            }
            if (type) {
                data.type = type;
            }
            const res = await api.post({
                url: `${url}/api/manage/rank`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatRankList', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setRankListLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setRankListReq', { key, req: false });
            return res;
        },
    },
};

export default m;
